package com.mobzilla.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.mobzilla.model.ExperienceAnalysis;
import com.mobzilla.model.User;
import com.mobzilla.util.Constants;
import com.mobzilla.util.Lock;

public class LoadBalancerServiceImpl implements LoadBalancerService {

	@Override
	public List<User> getTopUsersFromList(int count) {

		if (count <= 0) {
			return new ArrayList<User>();
		}

		String url = Constants.LOAD_BAL_TOPUSERS_PREFIX + "?count=" + count;

		return processUsersList(url);

	}

	@Override
	public List<User> getWorstUsersFromList(int count) {

		if (count <= 0) {
			return new ArrayList<User>();
		}

		String url = Constants.LOAD_BAL_WORSTUSERS_PREFIX + "?count=" + count;

		return processUsersList(url);

	}
	
	@Override
	public List<ExperienceAnalysis> getExperienceAnalysis() {
		String url = Constants.LOAD_BAL_EXP_ANALYSIS;
		
		Lock<String> lock = new Lock<String>();
		HTTPRequestAsync async = new HTTPRequestAsync(url, lock);
		async.execute();

		while (!lock.isDataSet()) {
			// Do Nothing
		}

		if (lock.getData() == null) {
			return null;
		}
		
		Gson gson = new Gson();
		ExperienceAnalysis[] response = gson.fromJson(lock.getData(), ExperienceAnalysis[].class);

		if (response == null) {
			return new ArrayList<ExperienceAnalysis>();
		}
		return Arrays.asList((ExperienceAnalysis[]) response);
		
	}

	private List<User> processUsersList(String url) {
		Lock<String> lock = new Lock<String>();
		HTTPRequestAsync async = new HTTPRequestAsync(url, lock);
		async.execute();

		while (!lock.isDataSet()) {
			// Do Nothing
		}

		if (lock.getData() == null) {
			return null;
		}

		Gson gson = new Gson();
		User[] response = gson.fromJson(lock.getData(), User[].class);

		if (response == null) {
			return new ArrayList<User>();
		}
		return Arrays.asList((User[]) response);
	}

}
